###############################################################################
# Copyright (C) 2010 Chris Wroe
#
# Modifications to the initial code base are copyright of their respective
# authors, or their employers as appropriate.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at your option)
# any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307
##############################################################################
require "rubygems" 
require "neo4j"
require "model"
require "lucene"
include Lucene

require "load_snomed_component"
require "field_to_property_map"

class LoadSnomedConceptComponent < LoadSnomedComponent

  attr_accessor :field_mapper

  def initialize(format_file)

    @field_mapper = FieldToPropertyMap.new
    @field_mapper.load_config(format_file)
    @rtype = org.neo4j.graphdb.DynamicRelationshipType.withName(Concept.class.to_s)
    super()
  end

  def create_component(line,inserter, global_properties)
    throw Exception if !line or line.strip.empty?
    @field_mapper.data=line


    current_concept_properties = {'_classname'=>'Concept'}.merge!(global_properties)
    current_concept_properties.merge! @field_mapper.property_map
   
    
    node_id = inserter.createNode(current_concept_properties)
    
    inserter.createRelationship(@index_node_id,node_id,@rtype,nil)

    @concept_index << {:id => node_id.to_s ,
      :snomed_code => current_concept_properties['snomed_code'],
      :name => current_concept_properties['name'],
      :version => current_concept_properties['version']
      }

  end

  def batch_insert_from_file(f,global_properties)
    component_inserted_count =0


    @concept_index = Index.new('/Concept')
    @concept_index.field_infos[:name][:tokenized] = true
    #@concept_index.field_infos[:name][:store]= true
    Neo4j::BatchInserter.new do |b|

      #skip header line
      read_row(f)

      while !f.eof?
        line = read_row(f)
        create_component(line,b,global_properties)
        component_inserted_count+=1
        if component_inserted_count % 75000 == 0
          puts component_inserted_count
          @concept_index.commit
          puts "Committed"
        end
      end
      @concept_index.commit

    end
    return component_inserted_count
  end

end
